<template>
<div class="form-cell">
  <van-field readonly clickable name="picker" :value="pickerValue" :label="label" :placeholder="placeholder || '请选择'"
    @click="showPicker = true" :rules="rules" :required="required === undefined ? false : true"/>
  <van-popup v-model="showPicker" position="bottom">
    <div class="van-picker__toolbar">
      <button type="button" class="van-picker__cancel" @click="showPicker = false">取消</button>
      <button type="button" class="van-picker__confirm" @click="onConfirm">确认</button>
    </div>
    <van-checkbox-group v-model="result"  style="height: 264px; overflow: auto;">
      <van-cell-group>
        <van-cell v-for="(item, index) in option" clickable :key="item.value"
          :title="item.label" @click="toggle(index)">
          <template #right-icon>
            <van-checkbox :name="item.value" ref="checkboxes" />
          </template>
        </van-cell>
      </van-cell-group>
    </van-checkbox-group>
  </van-popup>
</div>
</template>

<script>
export default {
  props: [ 'label', 'value', 'placeholder', 'option', "required", "rules" ],
  data() {
    return {
      result: [],
      pickerValue: '',
      showPicker: false,
    } 
  },
  watch: {
    value() {
      if (this.value && Array.isArray(this.value)) {
        this.result = JSON.parse(JSON.stringify(this.value));
        this.getShowValue();
        return ;
      }
      this.pickerValue = '';
    },
    option() {
      if (this.value && Array.isArray(this.value)) {
        this.result = JSON.parse(JSON.stringify(this.value));
        this.getShowValue();
        return ;
      }
      this.pickerValue = '';
    }
  },
  computed: {
    columns() {
      return this.option.map(item => item.label);
    }
  },
  methods: {
    toggle(index) {
      this.$refs.checkboxes[index].toggle();
    },
    getShowValue() {
      let pickerValue = [];
      this.result.forEach(ele => {
        let item = this.option.find(item => item.value === ele);
        if (item) {
          pickerValue.push(item.label);
        } else {
          pickerValue.push(ele);
        }
      });
      this.pickerValue = pickerValue.join('，');
    },
    onConfirm(label, index) {
      this.$emit('input', this.result);
      this.getShowValue();
      this.showPicker = false;
    }
  },
  mounted() {
    if (this.value && Array.isArray(this.value)) {
      this.result = JSON.parse(JSON.stringify(this.value));
      this.getShowValue();
    }
  }
}
</script>
